package com.yanqu.road.server.cmd.union.cross;

import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionConfigMgr;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.Map;

@Cmd(code = Protocol.C_UNION_QUERY, desc = "查看联盟")
public class CrossQueryUnionCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        UnionProto.UnionQueryReqMsg reqMsg = UnionProto.UnionQueryReqMsg.parseFrom(packet.getBytes());
        String unionUid = reqMsg.getUnionUid();

        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);

        if(unionInfo == null){
            ret = GameErrorCode.E_UNION_NO_FOUND;
        }

        UnionProto.UnionQueryRespMsg.Builder respMsg = UnionProto.UnionQueryRespMsg.newBuilder();
        respMsg.setRet(ret);
        if(unionInfo != null) {
            respMsg.setUnion(CrossUnionPb.parseUnionTempMsg(unionInfo));
            int crossServerCount = CrossUnionServerGroupMgr.getGroupServerCountByServerId(unionInfo.getServerId());
            respMsg.setMaxMemberCount(CrossUnionConfigMgr.getMaxMemberCount(unionInfo.getExperience(), unionInfo.isCross(), crossServerCount));
            Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionInfo.getUnionUid());
            if (null != memberMap) {
                for (CrossUnionMember member : memberMap.values()) {
                    UnionProto.UnionMemberTempMsg.Builder memberMsg = CrossUnionPb.parseUnionMemberTempMsg(member);
                    if (null != memberMsg) {
                        respMsg.addMemberList(memberMsg);
                    }
                }
            }
        }
        MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_UNION_QUERY, respMsg));

    }

    @Override
    public void sendData() {

    }
}
